package com.oem.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;

import com.oem.fragment.model.file.UploadFileParamsDto;
import com.oem.fragment.utils.FormUtils;

import java.util.Map;

public class UploadFragment extends Fragment {
    private Context context;

    private final ActivityResultLauncher<Intent> galleryLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                    Uri uri = result.getData().getData();
                    showUploadDialog(uri);
                }
            });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_upload, container, false);
        context = requireContext();

        Button galleryBtn = root.findViewById(R.id.btn_select_from_gallery);
        galleryBtn.setOnClickListener(view -> openGallery());

        Button urlUploadBtn = root.findViewById(R.id.btn_upload_url);
        urlUploadBtn.setOnClickListener(view -> showUrlUploadDialog());

        return root;
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        String[] mimeTypes = {"image/*", "video/*"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        galleryLauncher.launch(intent);
    }

    private void showUploadDialog(Uri fileUri) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_upload, null);

        ImageView imagePreview = dialogView.findViewById(R.id.filePreview);
        VideoView videoPreview = dialogView.findViewById(R.id.videoPreview);
        LinearLayout formContainer = dialogView.findViewById(R.id.formContainer);

        // 预览文件
        UploadHelper.showFilePreview(context, fileUri, imagePreview, videoPreview);

        // 构建输入框
        Map<String, EditText> fields = FormUtils.buildUploadFields(context);
        for (EditText field : fields.values()) formContainer.addView(field);

        builder.setView(dialogView)
                .setTitle("上传广告素材")
                .setPositiveButton("上传", (dialog, which) -> {
                    UploadFileParamsDto dto = UploadHelper.createUploadParams(fields);
                    UploadHelper.uploadFile(context, fileUri, dto);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.cancel())
                .create()
                .show();
    }

    private void showUrlUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        ScrollView scrollView = new ScrollView(context);
        LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);

        Map<String, EditText> fields = FormUtils.buildUploadFields(context);
        EditText urlField = FormUtils.createEditText(context, "*URL（例如：https://xxx.com/file.zip）", InputType.TYPE_TEXT_VARIATION_URI);
        layout.addView(urlField);
        for (EditText field : fields.values()) layout.addView(field);
        scrollView.addView(layout);

        builder.setTitle("输入 URL 上传文件")
                .setView(scrollView)
                .setPositiveButton("上传", (dialog, which) -> {
                    String url = urlField.getText().toString().trim();
                    if (url.isEmpty()) {
                        Toast.makeText(context, "URL 不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    UploadFileParamsDto dto;
                    try {
                        dto = UploadHelper.createUploadParams(fields);
                    } catch (Exception e) {
                        Toast.makeText(context, "参数错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    UploadHelper.uploadFileFromUrl(context, url, dto);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.cancel())
                .create()
                .show();
    }

}